package com.ad.aidai.activitys.feedback;

import android.content.Context;

import com.ad.aidai.common.ADApp;
import com.ad.aidai.common.utils.CheckUtil;
import com.ad.aidai.network.NetWork;
import com.ad.aidai.network.StatusCodeFromNet;
import com.ad.aidai.network.result.NetResult;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by pure on 2017/2/14.
 */

public class FeedbackPresenter implements FeedbackContract.Presenter {

    private Context mContext;
    private FeedbackContract.View mView;
    private CompositeSubscription mSubscriptions;

    private List<String> imageUrls;

    private int imageCount = 0;

    public FeedbackPresenter(Context context, FeedbackContract.View view) {
        this.mContext = context;
        this.mView = view;
        mView.setPresenter(this);
        imageUrls = new ArrayList<>();
        imageUrls.add("");
        imageUrls.add("");
        imageUrls.add("");
    }

    @Override
    public void subscribe() {
        mSubscriptions = new CompositeSubscription();
    }

    @Override
    public void unSubscribe() {
        mContext = null;
        mView = null;
        mSubscriptions.clear();
        mSubscriptions = null;
    }

    @Override
    public List<String> getAddedImage() {
        return imageUrls;
    }

    private RequestBody createPartFromString(String descriptionString) {
        if (descriptionString == null) {
            descriptionString = "";
        }
        return RequestBody.create(
                MediaType.parse("multipart/form-data"), descriptionString);
    }

    @Override
    public void submit(String etFeedbackContent,String etContact,List<String> imageUrlsList) {
        mView.showLoading();

        Map<String, RequestBody> pathMaps = new HashMap<>();
        Map<String, String> maps = new HashMap<>();
        maps.put("feedbackUid", String.valueOf(ADApp.getUser().getUserId()));
        maps.put("feedbackContent", etFeedbackContent);
        maps.put("feedbackContact", etContact);

        for(String key : maps.keySet()) {
            pathMaps.put(key, createPartFromString(maps.get(key)));
        }

        File[] files = new File[imageCount];
        for (int i = 0; i < imageCount; ++i) {
            files[i] = new File(imageUrls.get(i));
        }
        MultipartBody.Part[] parts = new MultipartBody.Part[imageCount];
        for (int i = 0; i < imageCount; ++i) {
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), files[i]);
            parts[i] = MultipartBody.Part.createFormData("fileData", files[i].getName(), requestFile);
        }

        Observable<NetResult> observable;

        try {
            if (imageCount == 0) {
                observable = NetWork.getAccountOperationApi()
                        .submitFeedback(maps);
            } else {
                observable = NetWork.getAccountOperationApi()
                        .submitFeedbackImage(parts, pathMaps);
            }

            observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<NetResult>() {
                        @Override
                        public void onCompleted() {
                            mView.closeActivity();
                        }

                        @Override
                        public void onError(Throwable e) {
                            Logger.t("FeedbackPresenter").e(e.getMessage());
                            //关闭加载对话框
                            mView.closeLoading(false);
                        }

                        @Override
                        public void onNext(NetResult netResult) {
                            if (netResult.getCode() != StatusCodeFromNet.CODE_SUCCESS) {
                                Logger.t("FeedbackPresenter").e(netResult.toString());
                                mView.closeLoading(false);
                            } else {
                                mView.closeLoading(true);
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void deleteImage(int position) {
        imageCount--;
        imageUrls.remove(position);
        imageUrls.add("");
        mView.showFeedbackImage(imageUrls.get(0), imageUrls.get(1), imageUrls.get(2));
    }

    @Override
    public void addImage(List<String> paths) {
        imageCount += paths.size();
        int position = 0;
        for (int i = 0; i < 3; ++i) {
            if(position < paths.size()) {
                if (CheckUtil.checkStrNull(imageUrls.get(i))) {
                    imageUrls.add(i, paths.get(position++));
                    imageUrls.remove(i + 1);
                }
            }
        }
        mView.showFeedbackImage(imageUrls.get(0), imageUrls.get(1), imageUrls.get(2));
    }

    @Override
    public int getImageCount() {
        return imageCount;
    }

    @Override
    public String getImageUrl(int position) {
        return imageUrls.get(position);
    }
}
